import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import getPageTitle from '@/utils/pageTitle';
import type { RouteLocationNormalized, Router } from 'vue-router';

let userStore: ReturnType<typeof useUserStore>;

const whitelist = ['/login'];

let nextGuard = true;

function loginGuard(to: RouteLocationNormalized) {
  NProgress.start();
  if (!userStore) {
    userStore = useUserStore();
  }
  nextGuard = true;

  if (userStore.token) {
    return to.path === '/login' ? { path: '/' } : true;
  }

  if (whitelist.includes(to.path)) {
    nextGuard = false;
    return true;
  }

  return {
    path: '/login'
  };
}

async function userGuard(to: RouteLocationNormalized) {
  if (!nextGuard) {
    return true;
  }
  document.title = getPageTitle(to.meta.title as string)
  if (userStore.user?.id) {
    return true;
  } else {
    const [route] = await Promise.all([userStore.getMenuList(), userStore.getUserInfo()]);
    if (to.path === '/') {
      return route ? { path: route.path, replace: true } : false;
    }
    return { ...to, replace: true }
  }
}
// async function ignoreGuard(to: RouteLocationNormalized) {
//   NProgress.start();
//   const userStore = useUserStore();
//   if (userStore.menuList.length === 0) {
//     await userStore.getMenuList();
//     return { ...to, replace: true };
//   }
//   return true;
// }

export default function (router: Router) {
  // if (import.meta.env.DEV) {
  //   router.beforeEach(ignoreGuard);
  //   return;
  // }
  [loginGuard, userGuard].forEach((guard) => {
    router.beforeEach(guard);
  });
}
